#!/bin/bash

# Linux Environment Variable Manager Debian Package Builder

set -e

# 获取项目根目录
PROJECT_DIR="$(cd "$(dirname "$0")" && pwd)"
# 修改: 直接指向项目根目录下的debian目录
DEBIAN_DIR="$PROJECT_DIR/debian"
# 修改: 将构建目录设置为脚本所在目录
BUILD_DIR="$PROJECT_DIR"
PACKAGE_NAME="linux-environment-variable-manager"

echo "Building Debian package for Linux Environment Variable Manager..."

# 检查必要文件是否存在

if [ ! -d "$DEBIAN_DIR" ]; then
    echo "Error: debian directory not found!"
    exit 1
fi

# 自动增加版本号
# 修改: 直接使用DEBIAN目录中的changelog文件
CHANGELOG_FILE="$DEBIAN_DIR/DEBIAN/changelog"

if [ -f "$CHANGELOG_FILE" ]; then
    # 从changelog中提取当前完整版本号 (例如: 1.0.48-1)
    CURRENT_FULL_VERSION=$(head -n 1 "$CHANGELOG_FILE" | sed -E 's/.*\(([^)]+)\).*/\1/')
    
    # 分离版本号和修订号
    CURRENT_VERSION=$(echo "$CURRENT_FULL_VERSION" | cut -d'-' -f1)
    CURRENT_REVISION=$(echo "$CURRENT_FULL_VERSION" | cut -d'-' -f2)
    
    # 使用更可靠的版本号递增方法
    # 提取主版本号、次版本号和修订号
    IFS='.' read -ra VERSION_PARTS <<< "$CURRENT_VERSION"
    MAJOR=${VERSION_PARTS[0]}
    MINOR=${VERSION_PARTS[1]}
    PATCH=${VERSION_PARTS[2]:-0}  # 默认为0
    
    # 增加修订版本号
    NEW_PATCH=$((PATCH + 1))
    NEW_VERSION="$MAJOR.$MINOR.$NEW_PATCH"
    
    # 新的修订号重置为1
    NEW_REVISION=1
    
    echo "当前版本: $CURRENT_VERSION-$CURRENT_REVISION, 新版本: $NEW_VERSION-$NEW_REVISION"
    
    # 更新changelog文件中的版本号
    sed -i "1s/($CURRENT_FULL_VERSION)/($NEW_VERSION-$NEW_REVISION)/" "$CHANGELOG_FILE"
    
    # 更新control文件中的版本号 (修复路径问题)
    sed -i "s/Version: .*/Version: $NEW_VERSION-$NEW_REVISION/" "$DEBIAN_DIR"/DEBIAN/control
    
    # 更新linux-environment-variable-manager.py中的版本信息（如果存在）
    APP_PY="$DEBIAN_DIR/usr/share/linux-environment-variable-manager/linux-environment-variable-manager.py"
    if [ -f "$APP_PY" ]; then
        # 只有在文件包含版本信息时才更新
        if grep -q "version = " "$APP_PY"; then
            sed -i "s/version = \".*\"/version = \"$NEW_VERSION\"/" "$APP_PY"
        else
            # 如果没有version变量，则在show_about函数中添加版本信息
            sed -i "s/version = \".*\"/version = \"$NEW_VERSION\"/" "$APP_PY" || \
                sed -i "/def show_about(self):/a\        version = \"$NEW_VERSION\"" "$APP_PY"
        fi
    fi
else
    echo "错误: 未找到changelog文件"
    exit 1
fi

# 设置权限
chmod 755 "$DEBIAN_DIR"/DEBIAN/*
chmod 755 "$DEBIAN_DIR"/usr/bin/linux-environment-variable-manager
chmod 755 "$DEBIAN_DIR"/usr/share/linux-environment-variable-manager/linux-environment-variable-manager.py

# 构建deb包
echo "构建deb包..."
cd "$PROJECT_DIR"
# 使用带版本号的包名
DEB_FILENAME="${PACKAGE_NAME}_${NEW_VERSION}-${NEW_REVISION}_all.deb"
# 修改: 直接打包debian目录，生成文件放在脚本所在目录
dpkg-deb --build debian "$DEB_FILENAME"

echo "Debian package built successfully!"
echo "Package location: $PROJECT_DIR/$DEB_FILENAME"

# 显示生成的文件
ls -la "$DEB_FILENAME"

echo "构建脚本执行完毕"